﻿


import Request from "../../base/request.js?t=202511041006"
import Storage from "../../base/storage.js?t=202511041006"
import { imageBaseUrl, downloadfun, isImageFile, IgetDeptList, DeleteModuleFile, queryURLParams, dealTime, getBrowserInfo, getRecentYears, CONSTPARAMSDATA} from "../../base/utils.js?t=202511041006"
const Composition = (proxy) => {
    const generateh = (text, isShort) => {
        if (isShort) {
            return h('div', {
                style: "width:100px;overflow:hidden;white-space: nowrap;text-overflow: ellipsis; -o-text-overflow: ellipsis;cursor:pointer"
            }, { default: () => text })
        } else {
            return h('div', {
                style: "width:300px;height:auto;"
            }, { default: () => text })
        }
    }
    const data = reactive({
        pdfOpen: false,
        pdfurl: "",

        uniDesc:"",
        messageTest: "",
        proxy: "",
        popShow: false,
        imgUrl: "",
        previewShow: false,
        isPermiss:false,
        uploadImg: {
            previewVisible: false,
            previewImage: "",
            previewTitle: "",
            fileList: [

            ]
        },
        yearlist:[],
        isAll: false,
        itemRender: (data) => {

            let uid = data.file.uid
            const previewBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnPreview(uid) }, src: "../Bussiness/img/svg/preview.svg", width: 20, height: 22 }, { default: () => '预览' })
            const downloadBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', onclick: () => { methods.btnDownLoad(uid) }, src: "../Bussiness/img/svg/download.svg", width: 20, height: 22 }, { default: () => '下载' })
            const deleteBtn = h('img', { style: 'cursor:pointer;margin:0 4px;', src: "../Bussiness/img/svg/delete.svg", width: 18, height: 22 }, { default: () => '删除' })
            const FDBtn = h(antd.Popconfirm, {
                title: "确定删除此文件？确定后不可恢复",
                onConfirm: () => methods.btnDelete(data)

            }, { default: () => [deleteBtn] })
            var btns = h('div', { style: "display:flex;margin-left:10px" }, {
                default: () => [
                    isImageFile(data.file.url) ? previewBtn : null,
                    downloadBtn,
                    params.urlinfo.value.type == 9 ? null : FDBtn
                ]
            })

     

            return h('div', { style: 'margin-top:10px; width:400px;align-items:center; display:flex;justify-content:space-between' }, {
                default: () => [
                    data.file.name, btns
                ]
            })

        },
        typelist: CONSTPARAMSDATA.typelist,
        editUploadList: [],
        uploadLock: false,
        deptList: [],
        formData: {
            DepartmentId: null,
            Title: null,
            Years:null,
            Remark: null,
            Type:1,
            Total: 0,
            Content:null,
            ReduceCount: 0,
            ReduceDescription:null,
            IncreaseCount: 0,
            IncreaseDescription: null,
            Total_A: 0,
            Total_B: 0,
            Total_C: 0,
            Total_D: 0,
        },
        rules: {
            ReduceDescription: [{ required: true, message: '请填写新增描述', trigger: 'change' }],
            IncreaseDescription: [{ required: true, message: '请填写删除描述', trigger: 'change' }],
            Title: [{ required: true, message: '请填写标题', trigger: 'change' }],
        },
        urlinfo: {},


    })
    let params = toRefs(data)
    const methods = {
        setVisible: (value) => {
            params.previewShow.value = value;
        },
        nchange: () => {

            if (+params.formData.value.ReduceCount > 0) {
                params.rules.value.ReduceDescription[0].required = true
            
            } else {
                params.rules.value.ReduceDescription[0].required = false
              
            }

            if (+params.formData.value.IncreaseCount  > 0) {
                params.rules.value.IncreaseDescription[0].required = true

            } else {
                params.rules.value.IncreaseDescription[0].required = false

            }


        },
        btnPreview: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            if (item.url.indexOf('.pdf') != -1) {
                params.pdfurl.value = item.url
                params.pdfOpen.value = true
            } else {
                params.imgUrl.value = item.url

                methods.setVisible(true)
            }
        },
        btnDownLoad: (e) => {
            let item = params.uploadImg.value.fileList.find(es => es.uid == e)
            item.url = item.FilePath || item.url
            const { name, url } = item
            downloadfun(name, url)

        },
        getDetailInfo: () => {
            params.uploadLock.value=true
            Request({
                url: "/SafetySystem/GetModuleFormDetail",
                method: 'post',
                data: {
                    Id: params.urlinfo.value.id
                }
            }).then(res => {
                params.formData.value = res.Data
                params.uploadImg.value.fileList = res.Data.FileList.map(e => {
                    return {
                     url: e.FilePath,
                     FileId: e.FileId,
                     name: e.FileName
                    }
                })
            }).finally(() => {
                params.uploadLock.value = false
            })




            
        },
        btnDelete: (e) => {
 
            const { FileId } = e.file
            if (FileId) {
                params.uploadLock.value = true
                DeleteModuleFile(Request, FileId).then(res => {
                    params.uploadImg.value.fileList = params.uploadImg.value.fileList.filter(e => e.FileId != FileId)
                    params.messageTest.value.success(res.Msg);
                }).finally(() => {
                    params.uploadLock.value = false
                })
            }
        },
        handleChange: (info) => {
            if (!params.uploadLock.value) {
                params.uploadLock.value = true
                let formData = new FormData();
                formData.append('nfile', info.file.originFileObj)
                formData.append('uid', info.file.originFileObj.uid)
                Request({
                    url: `/download/uploadfile?Path=/Module/${params.urlinfo.value.target.split('|')[1]}/`,
                    method: 'post',
                    data: formData
                }).then(res => {
                    let item = params.uploadImg.value.fileList.find(e => e.uid == res.Data[0].uid)
                    delete item.xhr
                    delete item.response
                    item.url = imageBaseUrl + res.Data[0].FilePath.split('../..')[1]
                    item.FileId = res.Data[0].FileId
                    item.FileName = res.Data[0].FileName
                    item.name = res.Data[0].FileName
                    params.uploadLock.value = false
     

                })

            }
        },

        filterOption: (val, type) => {
            return `${type.label}`.includes(`${val || ''}`)
        },

        getBase64: (file) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
            })
        },

        handlePreview: async (file) => {

            if (!file.url && !file.preview) {
                file.preview = (await methods.getBase64(file.originFileObj));
            }
            params.uploadImg.value.previewImage = file.url || file.preview;
            params.uploadImg.value.previewVisible = true;
            params.uploadImg.value.previewTitle = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
        },

        onSubmit(Status) {
            params.proxy.value.$refs.FormRule.validate().then(() => {
                if (params.urlinfo.value.type == 1) {
                    Request({
                        url: "/SafetySystem/EditModuleForm",
                        method: 'post',
                        data: {
                            model: {
                                Id: params.urlinfo.value.id,
                                "ModuleId": params.urlinfo.value.target.split("|")[1], //模块ID
                                ...params.formData.value
                            },
                            FileList: params.uploadImg.value.fileList.filter(e => e.size).map(e => e.FileId)

                        },
                    }).then(res => {
                        params.messageTest.value.success(res.Msg);
                        if (res.Code != -100) {
                            setTimeout(() => {
                                window.history.back()
                            }, 800)
                        }
                 
                    })
                } else {
                    Request({
                        url: "/SafetySystem/AddModuleForm",
                        method: 'post',
                        data: {
                            model: {
                                "ModuleId": params.urlinfo.value.target.split("|")[1], //模块ID
                                ...params.formData.value
                            },
                            FileList: params.uploadImg.value.fileList.filter(e => e.size).map(e => e.FileId)

                        },
                    }).then(res => {
                        params.messageTest.value.success(res.Msg);
                        if (res.Code != -100) {
                            setTimeout(() => {
                                window.history.back()
                            }, 800)
                        }

                    })
                }
              
            }).catch((res) => {
                params.messageTest.value.info(res.errorFields[0].errors[0]);
            })
        },
        getDeptList: () => {
            return new Promise(async (resolve, rej) => {
                params.deptList.value = await IgetDeptList(Request)
                if (params.deptList.value) {
                    resolve(1)
                }
            })
        },
        onBack: () => {
            window.history.back()
        },

        init: () => {
            getBrowserInfo().catch(err => { console.log(err) })
            params.urlinfo.value = queryURLParams()
            params.yearlist.value = getRecentYears()
            params.formData.value.Years = dayjs().format('YYYY')
            params.uniDesc.value = {
                'IOHS': '危险源识别表',
                'EFI': '环境因素辨识表',
                'UR': '不可接受风险',
                'HKEF': '重要环境因素',
            }[params.urlinfo.value.target.split("|")[0]]
    

            let info = Storage.get('AccountInfo', true)
            Request({
                url: "/Account/createJwtToken",
                method: 'post',
                data: {
                    "userName": info && info.UserNo
                }
            }).then(res => {

                Storage.set('token', res.Data,true)
           
                if (params.urlinfo.value.id) {
                    methods.getDeptList().then(res => {

                        methods.getDetailInfo()

                    })
                } else {
                    methods.getDeptList().then(res => {

                        params.formData.value.DepartmentId = Storage.get('AccountInfo', true).DepartmentId

                    })
                }
                methods.nchange()
                params.isPermiss.value = Storage.get('AccountInfo', true).DepartmentId!=20

            })


            if (proxy) {
                params.proxy.value = proxy
            }
            const { message } = antd
            params.messageTest.value = message
            params.messageTest.value.config({
                top: `10vh`,
                duration: 7,
                maxCount: 1,
                rtl: true,
            });

        },

    }
    const template = {
        pdfPopModel: {
            template: `
           <a-modal v-model:open="pdfOpen" width= "80%" title = "PDF预览" v-on:ok="pdfOpen=false" >
<div style='height:700px'>
                <embed id="pdfviewscreen" :src="pdfurl" type="application/pdf" width="100%" style="height:100%;" />

</div>
  
            </a-modal >
`,
            setup() {
                return {
                    ...params,
                    ...methods,
                };
            }
        },


        bottomBtns: {
            template: `<div class="w-full bg-[#eeeeee] h-50  flex  items-center justify-end pr-4">
                    <a-space>


  <a-popconfirm
    title="确定执行此操作?"
    ok-text="确定"
    cancel-text="取消"
    @confirm="onSubmit(1)"
  >
          <a-button  :loading="uploadLock" v-if="urlinfo.type!=9" type="primary">提交</a-button>
  </a-popconfirm>
                       
              
                        <a-button v-on:click="onBack" :loading="uploadLock">返回</a-button>
                    </a-space>
                </div>`,
            setup() {

                return {
                    ...params,
                    ...methods,
                };
            }

        }
    }
    return {
        ...params,
        ...methods,
        template
    }
}
export default Composition